#include "filter.h"


namespace evm { namespace messaging {

NotifyFilter::NotifyFilter(const Json &args) {
    if (args.count("publisher_id")) {
        string pattern = args["publisher_id"];
        publisher_id = make_shared<RegexObject>(pattern);
    }
    if (args.count("event_type")) {
        string pattern = args["event_type"];
        event_type = make_shared<RegexObject>(pattern);
    }
    if (args.count("timestamp")) {
        string pattern = args["timestamp"];
        timestamp = make_shared<RegexObject>(pattern);
    }
    if (args.count("payload"))
        for (auto it = args["payload"].cbegin(); it != args["payload"].cend(); ++it) {
            string pattern = it.value();
            payload[it.key()] = make_shared<RegexObject>(pattern);
        }
}

bool NotifyFilter::match(const Json& args) {
    if (publisher_id) {
        string arg = args["publisher_id"];
        if (!publisher_id->match(arg))
            return false;
    }

    if (event_type) {
        string arg = args["event_type"];
        if (!event_type->match(arg))
            return false;
    }

    if (timestamp) {
        string arg = args["timestamp"];
        if (!timestamp->match(arg))
            return false;
    }

    const Json& arg = args["payload"];

    for (auto& item: payload) {
        if (!arg.count(item.first))
            return false;
        string value = arg[item.first];
        if (!item.second->match(value))
            return false;
    }

    return true;
}

}}
